package com.kx.game.center.servlet;

import com.kx.game.center.bean.UserBean;
import com.kx.game.center.common.PlayerEnum;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出记录
 */
@WebServlet(urlPatterns = "/logout")
public class LogoutServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(LogoutServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            GSServices.loadManager.redisState();
            String wechatId = request.getParameter("userName");
            String serverId = request.getParameter("serverId");
            //更新人数
            GSServices.localManager.incrementGSLoginCount(serverId, -1);
            UserBean userInfo = GSServices.userManager.getUserInfo(wechatId);
            userInfo.setUserState(PlayerEnum.LOGOUT.getIndex() + "");
            userInfo.setLastUpdateTime(System.currentTimeMillis() + "");
            GSServices.userManager.saveUserInfo(userInfo); //保存redis
            GSServices.gameManager.printLog(request, logger, "玩家注销");
            GSServices.localManager.sendMessage(response, true, null, "");
        } catch (Exception e) {
            e.printStackTrace();
            GSServices.localManager.sendMessage(response, false, LocalErrorResponseCode.SYSTEM_ERROR, "");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
